SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[paEjecutarPasoDES]

@IdTramite INT,
@Decision INT

AS
SET NOCOUNT ON
DECLARE @Error INT
SET @Error = 0
DECLARE @Tracking INT
DECLARE @Paso INT
DECLARE @TareaPosterior INT
DECLARE @ReparticionDestino INT
DECLARE @Responsable INT

BEGIN TRANSACTION 

-- Obtengo el tracking que quiero actualizar
SELECT @Tracking = TR.IdTracking, @Paso = P.IdPaso, @TareaPosterior = CASE @Decision WHEN 0 THEN T.Posterior ELSE T.Posterior2 END, @ReparticionDestino = ReparticionDestino, @Responsable = Responsable
	FROM tb_Tracking TR 
	INNER JOIN tb_Tareas T ON TR.Tarea = T.IdTarea 
	INNER JOIN tb_Pasos P ON P.Tarea = T.IdTarea
	WHERE T.Tipo = 4 AND Tramite = @IdTramite AND TR.Estado = 4

-- Actualizo el tracking
UPDATE tb_Tracking SET Hasta = GETDATE(), Estado = 7 WHERE IdTracking = @Tracking

SELECT @Error = @@ERROR

IF @Error <> 0 GOTO Salir

-- Inserto el paso completado
INSERT tb_TrackingDePasos (Tracking, Paso, VistoBueno, Decision)
	VALUES(@Tracking, @Paso, 'S', @Decision)

SELECT @Error = @@ERROR

IF @Error <> 0 GOTO Salir

-- Inserto el tracking de la tarea posterior
INSERT INTO tb_Tracking (Tramite, NroSubtramite, Tarea, Desde, FechaRecepcion, FechaActivacion, Hasta, ReparticionDestino, Responsable, Estado)
	VALUES (@IdTramite, 0, @TareaPosterior, GETDATE(), NULL, NULL, NULL, @ReparticionDestino, @Responsable, 4)

SELECT @Error = @@ERROR

IF @Error <> 0 GOTO Salir

Salir:

IF @Error = 0
	COMMIT TRANSACTION
ELSE
	ROLLBACK TRANSACTION
GO
GRANT EXECUTE ON  [dbo].[paEjecutarPasoDES] TO [GestionDeDocumentos]
GO
